<template>
  <div class="container">
    <h2>用户登录</h2>
    <form @submit.prevent="handleLogin">
      <div class="form-group">
        <label for="userInput">用户名/邮箱号：</label>
        <input 
          type="text" 
          v-model="loginForm.userInput" 
          id="userInput" 
          name="userInput" 
          required 
        >
      </div>
      <div class="form-group">
        <label for="password">密码：</label>
        <input 
          type="password" 
          v-model="loginForm.password" 
          id="password" 
          name="password" 
          autofocus  
          required 
        >
      </div>
      <div v-if="loading" class="loading">正在登录...</div>
      <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
      
      <button type="submit" class="btn" :disabled="loading">登录</button>
    </form>
    <div class="links">
      <router-link to="/register">没有账号？立即注册</router-link><br>
      <router-link to="/reset">忘记密码？找回密码</router-link>

    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      loginForm: {
        userInput: this.$route.query.email || '', // 自动填充邮箱
        password: ''
      },
      loading: false,
      errorMessage: ''
    };
  },
  // 添加监听路由变化
  watch: {
    '$route.query.email'(newEmail) {
      if (newEmail) {
        this.loginForm.userInput = newEmail;
      }
    }
  },

  methods: {
    async handleLogin() {
      this.loading = true;
      this.errorMessage = '';

      try {
        const response = await axios.post('/api/login', this.loginForm);

        if (response.data.code === 2025) {
          // 管理员登录成功
          const admin = {
            aid: -1, // 前端临时ID，可根据需要修改
            username: this.loginForm.userInput,
            permissionLevel: 2, // 默认内容审核员，可根据实际情况调整
            isAdmin: true
          };

          localStorage.setItem('user', JSON.stringify(admin));
          localStorage.setItem('isAdmin', 'true'); // 标记为管理员

          this.$router.push({
            name: 'Admin', // 跳转到管理员仪表盘
          });
          return;
        } else if (response.data.code !== 200) {
          this.errorMessage = response.data.message || '登录失败，请重试';
          return;
        }

        const user = response.data.data;
        localStorage.setItem('user', JSON.stringify(user));
        // 将user参数通过路由的查询参数传递给HomePage页面
        this.$router.push({
          name: 'HomePage',
          query: {
            user: JSON.stringify(user)
          }
        });
      } catch (error) {
        if (error.response) {
          this.errorMessage = error.response.data.message || '登录失败，请重试';
        } else {
          this.errorMessage = '网络错误，请检查连接';
        }
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style src="../../assets/LoginMain.css"></style> <!-- 使用路径别名 -->
